<template>
	<view class="clothwrapper">
		<uni-forms :modelValue="formData" label-width="100">
			<uni-forms-item label="商品名称:" name="title">
				<uni-easyinput type="text" v-model="formData.title" placeholder="请输入商品名称" />
			</uni-forms-item>

			<view class="proimg">
				<view class="left">
					<view class="title" style="width:100%;height:80rpx;font-size:28rpx;font-weight: bold;color:orangered;line-height:80rpx;">商品主图</view>
					<view class="want">
						<view class="addimg">

							<view @tap="handleImage()">
								<view v-if="formData.image" class="item">
									<image :src="config.cdnurl+formData.image" mode="aspectFill"
										style="width:150rpx;height:150rpx"></image>
								</view>
								<view v-else class="item">
									<view class="text-lg text-gray text-item">
										<text class="wlIcon-tianjia"></text>
										<view class="margin-top-xs text-sm">添加图片</view>
									</view>
								</view>
							</view>
						</view>
					</view>

				</view>
				<!-- <view class="right">
					<view class="price">
						原价:<uni-easyinput type="text" v-model="formData.price"></uni-easyinput>元
						<view class="mid"></view>
						现价:<uni-easyinput type="text" v-model="formData.newprice"></uni-easyinput>元
					</view>
					<view class="store">
						库存:<uni-easyinput type="text" disabled v-model="formData.store"></uni-easyinput>
					</view>
				</view> -->

			</view>
			
			
			




			<view class="props">
				<view class="titlewrapper"  style="padding-top:20rpx;">
					<view class="name">商品规格</view>
					<view class="add" @click="addattr">+</view>
				</view>
				<view class="attrwrapper" v-for="(item,index) in attr" :key="index">
					<view class="close" @click="delattr(index)">X</view>
					
					<view class="left">
						<view class="colornameinput">
							<input placeholder="请输入颜色" v-model="item.colorname">
						</view>
						<view class="upimg">
							<view @tap="handleImagecolor(index)">
								<view v-if="item.image" class="item">
									<image :src="config.cdnurl + item.image" mode="aspectFill"
										style="width:150rpx;height:150rpx"></image>
								</view>
								<view v-else class="item">
									<view class="text-lg text-gray text-item" style="display:flex;align-items: center;">
										<text class="wlIcon-tianjia"></text>
										<view class="margin-top-xs text-sm">添加图片</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="right">
						<view class="listitem" v-for="(it,ind) in item.subattr" :key="ind">
							<view class="inputitem">
								<input placeholder="尺码" v-model="it.sizename"/>
							</view>
							<view class="inputitem">
								<input placeholder="单价" v-model="it.price"/>
							</view>
							<view class="inputitem">
								<input placeholder="库存" v-model="it.store"/>
							</view>
							<view v-if="ind == 0" class="tag" @click="addsubattr(index)">
								+
							</view>
							<view v-if="ind != 0" class="tag" @click="delsubattr(index,ind)">
								-
							</view>
						</view>						
					</view>					
				</view>
			
			</view>


			<view class="props">
				<view class="title">商品相册</view>
				<view class="wanlfind-add-container__main" style="padding-top:20rpx;margin-left:-20rpx;">
					<view class="grid col-4 grid-square flex-sub padding-lr-bj">
						<view v-if="descImages.length > 0" v-for="(item, index) in descImages" :key="index">
							<view class="item" style="width:150rpx;height:150rpx;" @tap="handlePreview2(index)">
								<image :src="$wanlshop.oss(item, 100, 100)" mode="aspectFill"></image>
							</view>
							<view class="tag" @tap="handleDelImage2(index)">
								<text class="wlIcon-31guanbi text-white"></text>
							</view>
						</view>			
						<view v-if="descImages.length < 8" @tap="handleImage2()">
							<view class="item">
								<view class="text-lg text-gray" style="width:150rpx;height:150rpx;border-radius: 10rpx;border:1rpx solid #aaa;display:flex;justify-content: center;align-items: center;">
									<text class="wlIcon-tianjia"></text>
									<view v-if="descImages.length === 0"  class="margin-top-xs text-sm">添加图片</view>
									<view v-else class="margin-top-xs text-sm">继续添加</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				
			</view>


		</uni-forms>
		<view class="btnwrapper">
			<button class="btn" @click="submitPro">提交</button>
		</view>
	</view>
</template>

<script>
	import config from "@/common/config/config.js"
	export default {
		data() {
			return {
				config,
				tag:"add",
				procolor: "", //属性颜色
				prosize: "", //属性尺寸

				spu: ['颜色', '尺码'],
				spuItem: [], //[['红','黄','蓝'], ['大','小']]
				sku: [],
				id:"",
				descImages:[], //商品相册
				
				attr:[
					{
						colorname:"",   //颜色
						image:"",
						subattr:[
							{
								sizename:"", //尺寸
								price:"", //单价
								store:""  //库存
							}
						]
					}
				],
			
				
				formData: {
					title: "", //商品标题
					//price: "", //商品价格
					//newprice: "", //现价 
					image: "", //商品主图
					//store: "", //库存
					description:"",
					stock:""
				}
			}
		},
		
		onLoad(options){
			let that = this;
			console.log(options);
			let detail = null;
			if(options.edit  && options.edit == 1){
				uni.setNavigationBarTitle({title:"编辑商品"});
				this.tag = "edit";
				detail = JSON.parse(options.detail);
				this.id = detail.id
				//如果是修改多规格的商品
				uni.request({
					url:"/wanlshop/shop/getSkuInfo",
					method:"POST",
					data:{id:detail.id},
					success(res){
						let goods = res.data.goods;
						let sku = res.data.sku;
						let spu = res.data.spu;
						let spuattr = [];
						let imageobj = {};
						sku.forEach(item=>{
							let colornamekey = item.difference.split(",")[0];
							imageobj[colornamekey] = item.thumbnail
						});
					
					
						//设置商品的主图
						that.formData.image = goods.image;
						that.formData.title = goods.title;
						that.descImages = goods.images.split(",");
					
					
					
						let attritem = {};
						let itemAttr = spu[0].item.split(",")
						that.attr = [];
						itemAttr.forEach(it=>{
							attritem = {
								colorname:it,
								image:imageobj[it],
								subattr:[],
							}
							let subattrobj = {}
							let subattrArr = [];
							sku.forEach(item=>{
								if(item.difference.indexOf(it) != -1){
									subattrobj = {
										sizename:item.difference.split(",")[1], //尺寸
										price:item.price, //单价
										store:item.stock  //库存
									}
									subattrArr.push(subattrobj);
								}
							})
							attritem.subattr = subattrArr;
							
							
							that.attr.push(attritem);
						})
					}
				})
				
				
				
				
			}
			
	
	
	
	
	
	
	
	
		},
		
		methods: {
			
			show(){
				console.log(this.attr);
			},
			
			
			delattr(index){
				if(this.attr.length == 1){
					return;
				}
				this.attr.splice(index,1);
			},
			
			
			addattr(){
				this.attr.push({
						colorname:"",   //颜色
						image:"",
						subattr:[
							{
								sizename:"", //尺寸
								price:"", //单价
								store:""  //库存
							}
						]				
					});
			},
			
			
			addsubattr(index){
				this.attr[index].subattr.push({
					sizename:"", //尺寸
					price:"", //单价
					store:""  //库存
				})
			},
			
			delsubattr(index,ind){
				this.attr[index].subattr.splice(ind,1);
			},
			
			
			
			makeSku(){
				let sku = [];  //[['红色','大',image,store]]
				this.attr.forEach(item=>{
					item.subattr.forEach(it=>{
						let skuitemArr = [];
						skuitemArr.push(item.colorname);
						skuitemArr.push(it.sizename);
						skuitemArr.push(item.image);
						skuitemArr.push(it.price);
						skuitemArr.push(it.store);
						sku.push(skuitemArr);
					})	
				})
				this.sku = sku;
			},
			
			makeSpuItem(){   //[['红','黄','蓝'], ['大','小']]
				let spuItem = []; 
				let map = new Map();
				let colorArr = [];
				let sizeArr = [];
				this.attr.forEach(item=>{
					colorArr.push(item.colorname);
					item.subattr.forEach(it=>{
						if(!map.has(it.sizename)){
							map.set(it.sizename,true);
							sizeArr.push(it.sizename);
						}
						
					})
				})
				this.spuItem = [colorArr,sizeArr];
			},
			
			
			
			submitPro(){

				if(!this.formData.title){
					uni.showToast({
						title:"商品名称不能为空",
						icon:"none"
					})
					return;
				}
				
				
				if(!this.formData.image){
					uni.showToast({
						title:"商品主图不能为空",
						icon:"none"
					})
					return;
				}
				

				this.makeSku();
				this.makeSpuItem();
				//从sku中找到最小的价格，做为主表中的商品价格
				
				
				let minprice = this.sku[0][3];
				this.sku.forEach(item=>{
					if(item[3]*1 <= minprice*1){
						minprice = item[3]
					}
				})
				
			
				try{
					this.sku.forEach(item=>{
						if(item.length<3){
							// uni.showToast({
							// 	title:"请完成各属性及库存设置",
							// 	icon:"none"
							// })
							throw new Error("请完成各属性及库存设置")
						}
						item.forEach((it,index)=>{
							
							if(index == 3){
								if(!it){
									throw new Error("商品的库存不能为空")
								}
							}
						})
					})
				}catch(e){
					uni.showToast({
						title:e.message,
						icon:"none"
					})
					return;
				}
				
				let params = {
					title:this.formData.title,
					image:this.formData.image,
					images:this.descImages.join(","),
					description:this.formData.description, //这个还没有设计，先给一个空值
					stock:'porder',
					freight_id:"13",
					spu:this.spu.join(","),
					spuItem:this.spuItem,
					sku:this.sku,
					price:minprice,
					tag:this.tag
				}
				if(this.tag == "edit"){
					params.id = this.id;
				}
				
				uni.request({
					url:"/wanlshop/shop/addClothGoods",
					method:"POST",
					data:params,
					success:(res)=>{
						console.log(res);
						if(res.res.code == 1){
							if(this.id){
								uni.showToast({
									title:"商品修改成功",
									icon:"none"
								})
							}else{
								uni.showToast({
									title:"商品添加成功",
									icon:"none"
								})
							}
							
							setTimeout(()=>{
								uni.navigateBack();
							},1500)
						}else{
							uni.showToast({
								title:"网络故障请重试",
								icon:"none"
							})
						}
					}
				})

			},
			
			
			
			
			
			inputStore($event,index){
	
				let value = $event.detail.value;
				if(this.sku[index].length == 2){
					this.sku[index].push("")
				}
				this.sku[index].splice(3,1,value);
				
			},
			
			
			handleImagecolor(index){
				let that = this;
				uni.chooseImage({
					crop: {
						quality: 60
					},
					success: res => {
						uni.request({
							url: '/wanlshop/common/uploadData',
							success: updata => {
								for (let i = 0; i < res.tempFilePaths.length; i++) {
									// 读取图片宽高
									uni.getImageInfo({
										src: res.tempFilePaths[i],
										success: image => {
											uni.uploadFile({
												url: updata.data.uploadurl,  ///api/common/upload
												filePath: image.path,
												name: 'file',
												formData:updata.data.storage == 'local' ? null : updata.data.multipart,
												success: data => {
													if(JSON.parse(data.data).code == 1){
														//this.params.images.push(JSON.parse(data.data).data.url);
														that.attr[index].image = JSON.parse(data.data).data.url;
													}
												},
												fail: error =>{
													uni.showToast({title: JSON.parse(error.data).msg, icon: 'error', position: true});
												}
											});
										}
									});
								}
							}
						});
					}
				});
							
			},
			
			
			handleImage2() {
				uni.chooseImage({
					crop: {
						quality: 60
					},
					count: 8, // 默认8
					success: res => {
						uni.request({
							url: '/wanlshop/common/uploadData',
							success: updata => {
								for (let i = 0; i < res.tempFilePaths.length; i++) {
									// 读取图片宽高
									uni.getImageInfo({
										src: res.tempFilePaths[i],
										success: image => {
											uni.uploadFile({
												url: updata.data.uploadurl,
												filePath: image.path,
												name: 'file',
												formData:updata.data.storage == 'local' ? null : updata.data.multipart,
												success: data => {
													this.descImages.push(JSON.parse(data.data).data.url);
												},
												fail: error =>{
													uni.showToast({title: JSON.parse(error.data).msg, icon: 'error', position: true});
												}
											});
										}
									});
								}
							}
						});
					}
				});
			},
			handlePreview2(index) {
				let imgArr = [];
				for (let item of this.descImages) {
					imgArr = imgArr.concat(this.$wanlshop.oss(item, 500));
				}
				uni.previewImage({
					urls: imgArr,
					current: imgArr[index],
					indicator: 'number'
				});
			},
			handleDelImage2(index) {
				this.descImages.splice(index, 1);
			},
			

			handleImage() {
				uni.chooseImage({
					crop: {
						quality: 60
					},
					success: res => {
						uni.request({
							url: '/wanlshop/common/uploadData',
							success: updata => {
								for (let i = 0; i < res.tempFilePaths.length; i++) {
									// 读取图片宽高
									uni.getImageInfo({
										src: res.tempFilePaths[i],
										success: image => {
											uni.uploadFile({
												url: updata.data.uploadurl,  ///api/common/upload
												filePath: image.path,
												name: 'file',
												formData:updata.data.storage == 'local' ? null : updata.data.multipart,
												success: data => {
													if(JSON.parse(data.data).code == 1){
														//this.params.images.push(JSON.parse(data.data).data.url);
														this.formData.image = JSON.parse(data.data).data.url;
													}
												},
												fail: error =>{
													uni.showToast({title: JSON.parse(error.data).msg, icon: 'error', position: true});
												}
											});
										}
									});
								}
							}
						});
					}
				});
			
			},
			
			
			
			handleImage1(index){
				let that = this;
				uni.chooseImage({
					crop: {
						quality: 60
					},
					success: res => {
						uni.request({
							url: '/wanlshop/common/uploadData',
							success: updata => {
								for (let i = 0; i < res.tempFilePaths.length; i++) {
									// 读取图片宽高
									uni.getImageInfo({
										src: res.tempFilePaths[i],
										success: image => {
											uni.uploadFile({
												url: updata.data.uploadurl,  ///api/common/upload
												filePath: image.path,
												name: 'file',
												formData:updata.data.storage == 'local' ? null : updata.data.multipart,
												success: data => {
													if(JSON.parse(data.data).code == 1){
														//this.params.images.push(JSON.parse(data.data).data.url);
														//this.formData.image = JSON.parse(data.data).data.url;
													
														that.sku[index].splice(2,1,JSON.parse(data.data).data.url)
														
														//查找所有的sku 的颜色值是否是一样的 如果是一样的就自动添加
														let currentSku = that.sku[index];
														let currentYS = currentSku[0];
														
														console.log(currentSku);
														console.log(currentYS);
														
														
														that.sku.forEach((item,ind)=>{
															console.log(item);
															if(item[0] == currentYS){
																that.sku[ind].splice(2,1,JSON.parse(data.data).data.url)
															}
														})
														
														
														
													}
												},
												fail: error =>{
													uni.showToast({title: JSON.parse(error.data).msg, icon: 'error', position: true});
												}
											});
										}
									});
								}
							}
						});
					}
				});
							
			},
			
			
			
			makeSkuItem() {
				if (!this.procolor) {
					uni.showToast({
						title: "请输入正码的色值",
						icon: "none"
					})
					return false;
				}
				if (!this.prosize) {
					uni.showToast({
						title: "请输入正确的尺码",
						icon: "none"
					});
					return false;
				}

				let arr1 = this.procolor.split(/\s+/)
				let arr2 = this.prosize.split(/\s+/)

				this.spuItem = [arr1, arr2];
				this.createSku()

			},
			createSku() {
				this.designSku(this.spuItem);
			},
			designSku(spuitem) {
				if (spuitem.length == 0) {
					this.sku = []
				}
				if (spuitem.length < 2) {
					spuitem[0].forEach((item) => {
						this.sku.push([item])
					})
				}

				let a = spuitem.shift();
				this.sku = spuitem.reduce((prev, curr) => {
					let res = [];
					if (!prev) {
						res = curr;
					} else {
						prev.forEach(item => {
							curr.forEach(it => {
								let t = [].concat(Array.isArray(item) ? item : [item]);
								t.push(it);
								res.push(t);
							})
						})
					}
					return res;
				}, a);

			}

		}
	}
</script>

<style lang="scss" scoped>
	.clothwrapper {
		width: 100%;
		padding: 20rpx 20rpx;
		min-height: 100vh;
		box-sizing: border-box;
		padding-bottom:80rpx;

		.btnwrapper{
			width:100%;
			height:80rpx;
			position:fixed;
			bottom:0;
			left:0;
			.btn{
				background:orangered;
				color:#fff;
			}
		}


		.props {
			
			.titlewrapper{
				display:flex;
				justify-content: flex-start;
				align-items: center;
				.name{
					color:orangered;
					font-weight: bold;
				}
				.add{
					margin-left:20rpx;
					padding:0;
					width:40rpx;
					height:40rpx;
					border-radius: 30rpx;
					display:flex;
					justify-content: center;
					align-items: center;
					border:1rpx solid #aaa;
					font-size:34rpx;
					font-weight: bold;
				}
				
			}
			.attrwrapper{
				margin-top:30rpx;
				position:relative;
				display:flex;
				justify-content: space-between;
				align-items: flex-start;
				.close{
					font-size:28rpx;
					color:#fff;
					width:40rpx;
					height:40rpx;
					position:absolute;
					right:0;
					top:-20rpx;
					border:1rpx solid  #aaa;
					border-radius: 30rpx;
					background:#aaa;
					text-align: center;
				}
				.left{
					flex-basis: 35%;
					padding:20rpx 10rpx;
					.colornameinput{
						input{
							width:100%;
							border:1rpx solid #aaa;
							height:60rpx;
							border-radius: 10rpx;
						}
					}
					.upimg{
						margin-top:20rpx;
						.item{
							width:100%;
							height:150rpx;
							display:flex;
							justify-content: center;
							align-items: center;
							background:#fff;
						}
					}
				}
				.right{

					flex:1;
					padding-left:30rpx;
					padding-top:10rpx;
					.listitem{
						display:flex;
						justify-content: flex-start;
						align-items: center;
						.inputitem{
							input{
								width:100rpx;
								height:50rpx;
								border:1rpx solid #aaa;
								margin:10rpx;
								border-radius: 10rpx;
								padding:5rpx;
							}
						}
						.tag{
							font-size:28rpx;
							width:40rpx;
							height:40rpx;
							border:1rpx solid #aaa;
							border-radius: 30rpx;
							line-height:32rpx;
							text-align: center;
							
						}
										
					}
					

				}
			}
			
			
			
			
			
			
			
			.title {
				width: 100%;
				color: orangered;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 28rpx;
				font-weight: bold;
			}

			.proitem {
				.color {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;
				}
			}

			.apply {
				display: inline;
				padding: 10rpx 30rpx;
				color: #fff;
				background: orange;
				float: right;
				box-sizing: border-box;
				border-radius: 10rpx;
			}

			.inputwrapper {
				width: 100%;
				clear: both;
				margin-top: 20rpx;

				.th {
					display: flex;
					justify-content: flex-start;
					align-items: center;

					.inputitem {
						width: 25%;
						text-align: center;
					}
				}

				.th1 {
					.inputitem {
						height: 150rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						.istore{
							border:1rpx solid #aaa;
							height:60rpx;
							width:100rpx;
							border-radius:10rpx;
						}
					}
				}
			}
		}


		.proimg {
			display: flex;
			justify-content: flex-start;
			align-items: flex-start;

			.left {
				.want {
					.addimg {
						width: 150rpx;
						height: 150rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						border: 1rpx solid #aaa;
						border-radius: 10rpx;

						.item {
							.text-item {
								display: flex;
								justify-content: center;
								align-items: center;
							}
						}
					}
				}
			}

			.right {
				padding-left: 50rpx;

				.price {
					display: flex;
					justify-content: flex-start;
					align-items: center;

					.mid {
						width: 30rpx;
					}

					::v-deep .uni-easyinput__content {
						width: 120rpx;
					}

				}

				.store {
					margin-top: 10rpx;
					display: flex;
					justify-content: flex-start;
					align-items: center;

					::v-deep .uni-easyinput__content {
						width: 180rpx;
					}
				}
			}


		}





	}
</style>